// 定义常量，为了复用，且代码提示
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class myPromise{
    constructor (executor){
        executor(this.resolve, this.reject)
    }
    // 定义状态，默然为等待
    status = PENDING
    // 成功之后的值
    value = undefined
    // 失败后的原因
    reason = undefined
    // 箭头函数是为了让this指向类的实例对象
    resolve = value => {
        // 如果状态不是等待，阻止程序向下执行
        if(this.status !== PENDING)  return
        // 状态改为成功
        this.status = FULFILLED
        // 保存成功之后的值
        this.value = value
    }
    reject = reason => {
        if(this.status !== PENDING)  return
        // 状态改为失败
        this.status = REJECTED
        // 保存失败后的原因
        this.reason = reason
    }
    then(successCallback, fillCallback){
        // 判断状态
        if(this.status == FULFILLED){
            successCallback(this.value)
        }else if(this.status == REJECTED){
            failCallback(this.reason)
        }
    }
}

module.exports = myPromise